package com.example.servlet;

import cn.hutool.json.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "login1", value = "/toLogin")
public class LoginServlet1 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp)
            throws ServletException, IOException {
        // 获取数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 定义响应方式
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        // 定义响应数据：一般包含3个部分，1：状态；2：报错信息；3：数据（查询功能）
        Map<String, Object> result = new HashMap<>();
        // 判断用户名是否为空，没有传username，就是null，传了但是没填写内容就是""
        if (username == null || username.trim().isEmpty()) {
            // 响应报错的提示
            result.put("status", false);
            result.put("msg", "未填写用户名");
            // 响应数据
            writer.write(JSONUtil.toJsonStr(result));
            writer.close();
            return;
        }
        // 判断密码是否为空，没有传password，就是null，传了但是没填写内容就是""
        if (password == null || password.trim().isEmpty()) {
            // 响应报错的提示
            result.put("status", false);
            result.put("msg", "未填写密码");
            // 响应数据
            writer.write(JSONUtil.toJsonStr(result));
            writer.close();
            return;
        }
        // username和password都是有数据的
        // 连接数据库校验账号和密码
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager
                    .getConnection("jdbc:mysql://localhost:3306/java_web_study",
                    "root", "123456");
            /*String sql = "select * from t_user where username = '"
                    + username + "' and password = '" + password + "'";
            System.out.println(sql);
            statement = connection.createStatement();*/
            /* 使用?占位符替换变量参数 */
            String sql = "select * from t_user where username = ? and password = ?";
            statement = connection.prepareStatement(sql);
            // 为?占位符赋值参数
            statement.setString(1, username);
            statement.setString(2, password);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                // 登录成功
                result.put("status", true);
            } else {
                // 登录失败
                result.put("status", false);
                result.put("msg", "用户名或密码错误");
            }
            writer.write(JSONUtil.toJsonStr(result));
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            // 报错了，响应一个报错提示
            // 数据库操作出错：连接失败、SQL语句不对
            // 加载驱动出错
            result.put("status", false);
            result.put("msg", "服务器内部出错，请联系管理员");
            writer.write(JSONUtil.toJsonStr(result));
            writer.close();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                result.put("status", false);
                result.put("msg", "服务器内部出错，请联系管理员");
                writer.write(JSONUtil.toJsonStr(result));
                writer.close();
            }
        }
    }
}
